package com.xiana.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @author <a href="mail to: 457066709@qq.com" rel="nofollow">Administrator</a>
 * @version v1.0
 * @package com.xiana.jedis
 * @project jedis-demo
 * @description [类型描述]
 * @createTime 2022/2/12 12:06
 */
public class PhoneCode {
    private static Jedis jedis;

    private final static Integer CODE_LENGTH = 6;
    private final static Integer DAY_MAX_COUNT = 3;
    private final static Integer CODE_EXPIRE_MINUTE_CODE = 2;
    private final static String KEY_PREFIX = "verifyCode_";
    private final static String KEY_COUNT_SUFFIX = "_count";
    private final static String KEY_CODE_SUFFIX = "_code";

    public static void main(String[] args) {
        sendCode("15867521803");
//        checkCode("15867521803","825771");
    }

    /**
     * 获取6位的随机数字验证码
     *
     * @return
     */
    public static String getCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code += random.nextInt(10);
        }
        return code;
    }



    /**
     * 1、输入手机号，点击发送后随机生成6位数字码，2分钟有效
     * 2、输入验证码，点击验证，返回成功或失败
     * 3、每个手机号每天只能输入3次
     */
    public static void sendCode(String phone) {
        //发送次数的key
        String phoneDayCount = KEY_PREFIX + phone + KEY_COUNT_SUFFIX;
        //发送手机的key
        String phoneCode = KEY_PREFIX + phone + KEY_CODE_SUFFIX;
        //判断每个手机号每天只能输入3次
        jedis = new Jedis("192.168.10.101", 6379);
        String redisPhoneDayCount = jedis.get(phoneDayCount);
        if (null == redisPhoneDayCount) {
            jedis.setex(phoneDayCount, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(redisPhoneDayCount) <= DAY_MAX_COUNT - 1) {
            jedis.incr(phoneDayCount);
        } else {
            System.out.println("今天发送次数已经超过三次");
            jedis.close();
            return;
        }

        //获取验证码，并保存2分钟有效
        String redisPhoneCode = getCode();
        jedis.setex(phoneCode, CODE_EXPIRE_MINUTE_CODE * 60, redisPhoneCode);
        jedis.close();
    }

    /**
     * 验证用户输入的code是否正确
     * @param phone
     * @param code
     */
    public static void checkCode(String phone,String code){
        //发送手机的key
        String phoneCode = KEY_PREFIX + phone + KEY_CODE_SUFFIX;

        jedis = new Jedis("192.168.10.101", 6379);
        String redisPhoneCode = jedis.get(phoneCode);
        if(code.equals(redisPhoneCode)){
            System.out.println("成功");
        }else{
            System.out.println("失败");
        }
    }
}
